package com.sczmgk.hotline_pzh.mainhomeUiView;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sczmgk.hotline_pzh.MyApp;
import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.MainHomeBaseView;
import com.sczmgk.hotline_pzh.callback.HttpFailCallback;
import com.sczmgk.hotline_pzh.callback.OnRefreshListener;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.ComplainInfo;
import com.sczmgk.hotline_pzh.entity.ComplaintSettingBean;
import com.sczmgk.hotline_pzh.entity.Picurls;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.ui.ComplaintCancleActivity;
import com.sczmgk.hotline_pzh.ui.ComplaintDetailActivity;
import com.sczmgk.hotline_pzh.ui.ComplaintEvaluteActivity;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.utils.MyLog;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.view.RefreshListView;
import com.shizhefei.view.indicator.Indicator;
import com.shizhefei.view.indicator.ScrollIndicatorView;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.jpush.android.api.b.j;
import static com.sczmgk.hotline_pzh.MyApp.bitmapUtils;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_CANCEL;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_EVALUTED;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_PRETREATMENTED;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_PRETREATMENT_FAIL;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_PROCESSING;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_WAITING_CHECK;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_WAITING_EVALUTE;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_WAITING_PRETREATMENT;
import static com.sczmgk.hotline_pzh.constants.Constants.STATUS_WAITING_PROCESS;

/**
 * Created by Administrator on 2016/11/21 0021.
 */
public class MainHomeComplaintSetting extends MainHomeBaseView {
    /**
     * 投诉处理的集合
     */
    private List<ComplainInfo> complaintInfos = new ArrayList<>();
    private int lastposition;

    /*投诉处理*/
    private static final int COMPLAINT_SETTING_INFO = 100;

    /*投诉的顶部图*/
    private ImageView ivComplaintIcon;

    /*指示器控件*/
    private ScrollIndicatorView indicator;

    /*投诉设置的内容*/
    private RefreshListView mLvComplaintSetting;

    /*投诉处理的内容adapter*/
    private MyAdapter adapter;

    /*空的图片的控件*/
    private LinearLayout mLayoutEmpty;

    /**
     * 附加list
     */
    private JSONArray extrasList;
    /**
     * 默认第一次加载
     */
    private final int LOAD_NORMAL = 0;
    /**
     * 下拉刷新状态
     */
    private final int PULL_REFRESH = 1;
    /**
     * 上拉加载更多
     */
    private final int LOAD_MORE = 2;

    /**
     * 已加载的页数
     */
    private int loadedPage;
    /**
     * 当前页
     */
    private int nowpage;
    /**
     * 总页数
     */
    private int totalpages;
    private String systemtime;
    private int count;
    private String keyword = "";
    private int lastVisiblePosition;
    private static final int REQUEST_CODE = 555;

    public MainHomeComplaintSetting(Activity context) {
        super(context);

        initView();

        setListener();

        initData();
    }

    @Override
    public void mHandleMessage(Message msg) {

        switch (msg.what) {
            case COMPLAINT_SETTING_INFO:

                //如果是正在刷新,隐藏头部局,展示内容
                mLvComplaintSetting.hideHeaderView();
                mLvComplaintSetting.hideFooterView();

                if (complaintInfos != null && complaintInfos.size() > 0) {
                    mLayoutEmpty.setVisibility(View.GONE);
                    mLvComplaintSetting.setEnablePullDown(true);

                    //如果是加载更多,选择最后一个位置
//                    mLvComplaintSetting.setSelection(complaintInfos.size() - 1);
                } else {
                    mLayoutEmpty.setVisibility(View.VISIBLE);
                    mLvComplaintSetting.setEnablePullDown(false);
                    mLvComplaintSetting.hideNotMore();
                }

                adapter.notifyDataSetChanged();

                MyLog.d(TAG, "刷新过后" + lastVisiblePosition + "");

//                int loadStatue = (int) msg.obj;
//                if (loadStatue == LOAD_MORE) {
//
//                    mHandler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            mLvComplaintSetting.setSelection(lastVisiblePosition + 1);
//                        }
//                    }, 100);
//                }

                break;
            case Constants.CHECK_COMPLAINT_VIEW:

                //访问网络拉取数据
                accessNetWord(1, LOAD_NORMAL);

                break;
        }
    }

    /**
     * 初始化控件
     */
    @Override
    public void initView() {

        View rootView = View.inflate(activity, R.layout.activity_complaint_setting, null);

        //顶部图
        ivComplaintIcon = (ImageView) rootView.findViewById(R.id.iv_complaint_setting_image);
        //指示器
        indicator = (ScrollIndicatorView) rootView.findViewById(R.id.indicator_complaint_setting);
        //投诉处理
        mLvComplaintSetting = (RefreshListView) rootView.findViewById(R.id.lv_complaint_setting);
        //投诉处理没有数据的显示图
        mLayoutEmpty = (LinearLayout) rootView.findViewById(R.id.ll_complaint_empty);

        //设置Indicator指示器
        indicator.setBackgroundResource(R.color.white);
        String[] indicatorTitle = activity.getResources().getStringArray(R.array.complaint_setting_indicator);
        CommonUtils.setIndector(indicator, indicatorTitle, activity);

        //将布局添加到容器中
        container.addView(rootView);
    }

    /**
     * 初始化数据
     */
    private void initData() {

        //设置adapter
        adapter = new MyAdapter();
        mLvComplaintSetting.setAdapter(adapter);

        //默认指示器选择0
        indicator.setCurrentItem(0);
    }

    /**
     * 设置监听
     */
    private void setListener() {

        //设置指示器的监听
        indicator.setOnItemSelectListener(new Indicator.OnItemSelectedListener() {

            @Override
            public void onItemSelected(View view, int itemPosition, int i1) {

                if (mLvComplaintSetting.isRefresh()) {
                    mLvComplaintSetting.hideHeaderView();
                }

                if (mLayoutEmpty.getVisibility() == View.VISIBLE) {
                    mLayoutEmpty.setVisibility(View.GONE);
                }

                if (loadingDialog != null && loadingDialog.isShowing()){
                    DialogFactory.dismissLoadingDialog(loadingDialog);
                }

                //指示器的条目选择
                indicatorSelected(itemPosition);
                lastposition = itemPosition;

            }
        });

        //下拉刷新
        mLvComplaintSetting.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                //访问网络拉取数据
                accessNetWord(1, PULL_REFRESH);
            }

            @Override
            public void onLoadingMore() {
                MyLog.i(TAG, "totalpages:　" + totalpages + "      nowpages :" + nowpage);
                if (totalpages > nowpage) {
                    loadData(nowpage + 1, keyword, LOAD_MORE);
                } else {
                    mLvComplaintSetting.hideNotMore();
                }
            }
        });

        mLvComplaintSetting.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int position = i - 1 ;
                Intent intent = new Intent(activity, ComplaintDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.COMPLAIN_INFO_KEY, complaintInfos.get(position));
                intent.putExtras(bundle);
                activity.startActivity(intent);
            }
        });

    }

    /**
     * 加载数据
     *
     * @param page
     * @param loadStatus
     */
    protected void loadData(final int page, String keyoword, final int loadStatus) {
        accessNetWord(page, loadStatus);
    }

    /**
     * 指示器的条目选择
     */
    private void indicatorSelected(int itemPosition) {

        if (lastposition == itemPosition) {
            return;
        }

        accessNetWord(1, LOAD_NORMAL);
    }

    /**
     * 根据状态访问网络
     *
     * @param page
     * @param loadStatus
     */
    public void accessNetWord(int page, final int loadStatus) {

//        lastVisiblePosition = mLvComplaintSetting.getLastVisiblePosition();
//        MyLog.d(TAG, "刷新之前" + lastVisiblePosition + "");

        if (!mLvComplaintSetting.isRefresh() || !mLvComplaintSetting.isShowNotMore()) {

            if (loadStatus == LOAD_NORMAL) {
                //清除集合,刷新listview
                if (complaintInfos.size() > 0) {
                    complaintInfos.clear();
                }
                adapter.notifyDataSetChanged();
            }
        }

        int staus = indicator.getCurrentItem();

        Map<String, Object> infos = new HashMap<>();
        infos.put("querystatus", staus);
        infos.put("page", page);
        infos.put("imei", MyApp.imei);
        infos.put("userid", CacheUtils.getIntData(activity, Constants.LOGIN_UID, 0));

        loadingDialog = mLvComplaintSetting.isRefresh() ? null : DialogFactory.getLoadingDialog(activity);
        DialogFactory.showDialog(loadingDialog);

        MyHttp.requestByFailCallback(Constants.BASE_URL + Constants.GET_COMPLAINTS_URL, infos, MyHttp.GET, activity, false, null, new SimplePaserJsonCallback() {

            @Override
            public void onVerifyIsNull() {
                if (mLvComplaintSetting.isRefresh()) {
                    mLvComplaintSetting.hideHeaderView();
                }

                mLvComplaintSetting.setEnablePullDown(false);
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
                DialogFactory.dismissLoadingDialog(loadingDialog);
                try {
                    paserComplaintJson(dataRaw, isCache, loadStatus);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    e.printStackTrace();
                }

            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                if (mLvComplaintSetting.isRefresh()) {
                    mLvComplaintSetting.hideHeaderView();
                }
                mLvComplaintSetting.setEnablePullDown(false);
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }
        }, new HttpFailCallback() {
            @Override
            public void onServiceErrorCallback() {
//                MyToast.show(activity, "您的网络有问题,请检查您的网络");
                //TODO 加载失败暂时显示空的图片
                if (mLvComplaintSetting.isRefresh()) {
                    mLvComplaintSetting.hideHeaderView();
                }
                DialogFactory.dismissLoadingDialog(loadingDialog);
            }
        });
    }

    /**
     * 处理投诉列表的Json数据
     *
     * @param dataRaw
     * @param isCache
     * @param loadStatus
     */
    private void paserComplaintJson(String dataRaw, boolean isCache, int loadStatus) {
        if (Tools.isEmpty(dataRaw)) {
            MyLog.i("获取投诉处理数据", "get ComplaintSetting json error");
            return;
        }

        //解析投诉处理数据并将数据添加到集合中
        Gson gson = new Gson();
        ComplaintSettingBean complaintSettingBean = gson.fromJson(dataRaw, ComplaintSettingBean.class);

        totalpages = complaintSettingBean.totalpages;
        nowpage = complaintSettingBean.nowpage;
        if (nowpage > loadedPage) { //缓存已加载的页数
            loadedPage = nowpage;
        }

        switch (loadStatus) {
            case LOAD_MORE:
                MyLog.i(TAG, "加载更多的第：" + nowpage + "  页");

                complaintInfos.addAll(complaintSettingBean.datalist);

                break;
            case LOAD_NORMAL:
            case PULL_REFRESH:
                if (nowpage == 1) {//加载的当前页是第一页
                    if (complaintInfos.size() > 0) {
                        MyLog.i(TAG, "初始化或下拉刷新的第一页，清空集合 ！");
                        complaintInfos.clear();
                    }
                }
                complaintInfos.addAll(complaintSettingBean.datalist);

                break;
        }

        //发送消息
        Message msg = Message.obtain();
        msg.obj = loadStatus;
        msg.what = COMPLAINT_SETTING_INFO;
        mHandler.sendMessage(msg);
    }

    @Override
    public void onResume() {
        super.onResume();

        //清除集合,刷新listview
//        if (complaintInfos.size() > 0) {
//            complaintInfos.clear();
//            adapter.notifyDataSetChanged();
//        }
//
//
//
//        //访问网络拉取数据
//        int currentItem = indicator.getCurrentItem();
//        accessNetWord(currentItem, 1, LOAD_NORMAL);
    }

    /**
     * listview的adapter
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return complaintInfos == null ? 0 : complaintInfos.size();
        }

        @Override
        public Object getItem(int position) {
            return complaintInfos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertview, ViewGroup viewGroup) {

            ViewHolder holder = null;

            if (convertview == null) {
                convertview = View.inflate(viewGroup.getContext(), R.layout.item_complaint_setting, null);
                holder = new ViewHolder();
                holder.ivComplaint = (ImageView) convertview.findViewById(R.id.iv_complaint_item_image);
                holder.tvComplaintState = (TextView) convertview.findViewById(R.id.tv_complaint_setting_state);
                holder.tvComplaintTitle = (TextView) convertview.findViewById(R.id.tv_complaint_setting_title);
                holder.tvComplaintDate = (TextView) convertview.findViewById(R.id.tv_complaint_setting_date);

                holder.btnCancleComplaint = (Button) convertview.findViewById(R.id.btn_cancle_complaint);
                holder.btnComplaintDetail = (Button) convertview.findViewById(R.id.btn_complaint_detail);
                holder.btnComplaintEvalute = (Button) convertview.findViewById(R.id.btn_complaint_evalute);
                holder.btnDeleteComplaint = (Button) convertview.findViewById(R.id.btn_delete_complaint);
                holder.btnComplaintHaveEvalute = (Button) convertview.findViewById(R.id.btn_complaint_have_evalute);

                convertview.setTag(holder);
            } else {
                holder = (ViewHolder) convertview.getTag();
            }

            final ComplainInfo complainInfo = complaintInfos.get(position);
            setBtnStatus(position, complainInfo, holder.btnComplaintHaveEvalute, holder.btnDeleteComplaint,
                    holder.btnCancleComplaint, holder.btnComplaintEvalute, holder.tvComplaintState);
            //设置投诉标题和时间
            holder.tvComplaintTitle.setText(complainInfo.title);
            holder.tvComplaintDate.setText(complainInfo.createtime);

            //设置图片
            holder.ivComplaint.setImageResource(R.drawable.complain_default_pic);
            List<Picurls> picurls = complainInfo.picurls;
            if (picurls != null && picurls.size() > 0) {
                bitmapUtils.display(holder.ivComplaint, picurls.get(0).smallpic);
            }

            //取消投诉的按钮
            holder.btnCancleComplaint.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(activity, ComplaintCancleActivity.class);
                    intent.putExtra(Constants.COMPLAIN_INFO_KEY, complainInfo);
                    activity.startActivityForResult(intent , Constants.COMPLAINT_REQUEST_CODE);
                }
            });

            //投诉详情的按钮
            holder.btnComplaintDetail.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(activity, ComplaintDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(Constants.COMPLAIN_INFO_KEY, complainInfo);
                    intent.putExtras(bundle);
                    activity.startActivity(intent);
                }
            });


            return convertview;
        }
    }

    private void setBtnStatus(final int position, final ComplainInfo complainInfo, Button btnComplaintHaveEvalute, Button btnDeleteComplaint,
                              Button btnCancleComplaint, Button btnComplaintEvalute, TextView tvComplaintState) {
        btnComplaintEvalute.setVisibility(View.GONE);
        btnCancleComplaint.setVisibility(View.GONE);
        btnDeleteComplaint.setVisibility(View.GONE);
        btnComplaintHaveEvalute.setVisibility(View.GONE);
        switch (complainInfo.status) {
            case STATUS_WAITING_CHECK:
            case STATUS_WAITING_PRETREATMENT:
            case STATUS_WAITING_PROCESS:
                btnComplaintEvalute.setVisibility(View.GONE);
                btnCancleComplaint.setVisibility(View.VISIBLE);
                btnDeleteComplaint.setVisibility(View.GONE);
                btnComplaintHaveEvalute.setVisibility(View.GONE);
                tvComplaintState.setText("待处理");
                break;
            case STATUS_PRETREATMENTED:
            case STATUS_PROCESSING:
                btnComplaintEvalute.setVisibility(View.GONE);
                btnCancleComplaint.setVisibility(View.VISIBLE);
                btnDeleteComplaint.setVisibility(View.GONE);
                btnComplaintHaveEvalute.setVisibility(View.GONE);
                tvComplaintState.setText("正在调查处理");
                break;
            case STATUS_WAITING_EVALUTE:
                btnComplaintEvalute.setVisibility(View.VISIBLE);
                btnCancleComplaint.setVisibility(View.GONE);
                btnDeleteComplaint.setVisibility(View.GONE);
                btnComplaintHaveEvalute.setVisibility(View.GONE);
                tvComplaintState.setText("已经处理完毕");
                //评价的按钮
                btnComplaintEvalute.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(activity, ComplaintEvaluteActivity.class);
                        intent.putExtra(Constants.COMPLAIN_INFO_KEY, complainInfo);
                        activity.startActivityForResult(intent , Constants.COMPLAINT_REQUEST_CODE);
                    }
                });
                break;
            case STATUS_EVALUTED:
                btnComplaintHaveEvalute.setVisibility(View.GONE);
                btnDeleteComplaint.setVisibility(View.VISIBLE);
                btnCancleComplaint.setVisibility(View.GONE);
                btnComplaintEvalute.setVisibility(View.GONE);
                tvComplaintState.setText("已评价");
                //删除投诉
                btnDeleteComplaint.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //TODO
                        deleteComplain(position, complainInfo);
                    }
                });
                break;
            case STATUS_CANCEL:
                btnDeleteComplaint.setVisibility(View.VISIBLE);
                btnCancleComplaint.setVisibility(View.GONE);
                btnComplaintEvalute.setVisibility(View.GONE);
                btnComplaintHaveEvalute.setVisibility(View.GONE);
                tvComplaintState.setText("已取消投诉");
                //删除投诉
                btnDeleteComplaint.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //TODO
                        deleteComplain(position, complainInfo);
                    }
                });
                break;
            case STATUS_PRETREATMENT_FAIL:
                btnComplaintEvalute.setVisibility(View.GONE);
                btnCancleComplaint.setVisibility(View.GONE);
                btnDeleteComplaint.setVisibility(View.VISIBLE);
                btnComplaintHaveEvalute.setVisibility(View.GONE);
                tvComplaintState.setText("预审失败");
                //删除投诉
                btnDeleteComplaint.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //TODO
                        deleteComplain(position, complainInfo);
                    }
                });
                break;

        }
    }

    private void deleteComplain(final int position, final ComplainInfo complainInfo) {
        Dialog dialog = DialogFactory.chooseDialog(activity, "删除后不可恢复,确定要删除?", R.string.sure, R.string.cancel, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String, Object> maps = new HashMap<>();
                maps.put("userid", CacheUtils.getIntData(activity, Constants.LOGIN_UID, 0));
                maps.put("id", complainInfo.id);
                MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_DELETE_COMPLAIN_URL, maps, MyHttp.POST, activity, false, null, new SimplePaserJsonCallback() {
                    @Override
                    public void onVerifyIsNull() {
                        DialogFactory.warningDialog(activity, "删除成功" ,R.string.sure, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                            }
                        });
                        complaintInfos.remove(position);
                        mHandler.sendEmptyMessage(COMPLAINT_SETTING_INFO);

                    }

                    @Override
                    public void onVerifySuccess(String dataRaw, boolean isCache) {

                    }

                    @Override
                    public void onErrorCodeError(BaseEntity.MyError mError) {
                        super.onErrorCodeError(mError);
                    }
                });
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        dialog.show();

    }

    private class ViewHolder {
        private ImageView ivComplaint;
        private TextView tvComplaintState;
        private TextView tvComplaintDate;
        private TextView tvComplaintTitle;

        private Button btnCancleComplaint;
        private Button btnComplaintDetail;
        private Button btnComplaintEvalute;

        private Button btnDeleteComplaint;
        private Button btnComplaintHaveEvalute;

    }

    @Override
    public void onPause() {
        super.onPause();
        if (mLvComplaintSetting.isRefresh()) {
            mLvComplaintSetting.hideHeaderView();
        }
    }
}
